#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>

#include "config.h"

static int should_query = 0;
static char package_name[25];
static char package_directory[50] = "~/.pk6/pkgdir";
static int should_start = 0;
static int should_run_daemon = 0;
static char port[9] = "8824";
static int should_stop_daemon = 0;

int main(int argc, char *argv[]) {
	int c;
	while (1) {
		static struct option long_options[] = {
			{"version", no_argument, 0, 'v'},
			{"help", no_argument, 0, 'h'},
			{"query", required_argument, 0, 'q'},
			{"package-directory", required_argument, 0, 'd'},
			{"start", no_argument, 0, 's'},
			{"start-daemon", no_argument, 0, 'D'},
			{"port", required_argument, 0, 'p'},
			{"stop-daemon", no_argument, 0, 'S'},
			{0, 0, 0, 0}
		};

		int option_index = 0;
		c = getopt_long(argc, argv, "vhq:d:s:D:p:", long_options, &option_index);
		
		if (c == -1) 
			break;
		
		switch (c) {
			case 0:
				if (long_options[option_index].flag != 0)
					break;
				printf("Unknown option: %s.\n", long_options[option_index].name);
				break;
			case 'v':
				printf("%s-server %s\n", PACKAGE, VERSION);
				break;
			case 'h':
				printf("%s-server\n--version, -v    print version information\n--help, -h    print help information\n--query, -q    search package repositories\n", PACKAGE);
				break;
			case 'q':
				should_query = 1;
				strncpy(package_name, optarg, sizeof(package_name));
				break;
			case 'd':
				strncpy(package_directory, optarg, sizeof(package_directory));
				break;
			case 'D':
				should_run_daemon = 1;
				break;
			case 's':
				should_start = 1;
				break;
			case 'p':
				strncpy(port, optarg, sizeof(port));
				break;
			case 'S':
				should_stop_daemon = 1;
				break;
			default:
				return 0;
		}
	}

	if (should_query == 1) {
		printf ("We will search all the directory %s for %s.\n", package_directory, package_name);
	}
	else if (should_start == 1) {
		printf ("We will start the server on port %s, with directory %s.\n", port, package_directory);
	}
	else if (should_run_daemon == 1) {
		printf ("We will start the server as a daemon on port %s, with directory %s.\n", port, package_directory);
	}
	else if (should_stop_daemon == 1) {
		printf ("We will stop the daemon running on port %s.\n", port);
	}

	return 0;
}
